package com.security.test.config;

import com.security.test.entity.MyUserDetail;
import org.springframework.security.authentication.AbstractAuthenticationToken;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.GrantedAuthority;

import java.util.Collection;

/**
 * @author songmin.hou
 */
public class MyUsernamePasswordAuthenticationToken extends AbstractAuthenticationToken {

    private String username;
    private String password;


    public MyUsernamePasswordAuthenticationToken(String username, String password, Collection<? extends GrantedAuthority> authorities) {
        super(authorities);
        this.username = username;
        this.password = password;
    }

    public MyUsernamePasswordAuthenticationToken(String username, String password) {
        super(null);
        this.username = username;
        this.password = password;
    }

    // 未认证时
    public static MyUsernamePasswordAuthenticationToken MyUsernamePasswordAuthenticationTokenUnAuthenticated(String username, String password) {
        MyUsernamePasswordAuthenticationToken token = new MyUsernamePasswordAuthenticationToken(null, null, null);
        token.username = username;
        token.password = password;
        token.setAuthenticated(Boolean.FALSE);
        return token;
    }

    // 认证成功后
    public static MyUsernamePasswordAuthenticationToken MyUsernamePasswordAuthenticationTokenAuthenticated(MyUserDetail myUser) {
        MyUsernamePasswordAuthenticationToken authenticationToken = new MyUsernamePasswordAuthenticationToken(null, null, myUser.getAuthorities());
        // 认证成功后，将密码清除
        myUser.getUser().setPassWord(null);
        // 设置为已认证状态
        authenticationToken.setAuthenticated(Boolean.TRUE);
        // 用户详情为MyUser
        authenticationToken.setDetails(myUser);
        return authenticationToken;
    }

    @Override
    public String getCredentials() {
        return this.password;
    }

    @Override
    public String getPrincipal() {
        return this.username;
    }

}
